package com.luych.toolbox.data.service.service;

import com.luych.toolbox.common.enums.DataTransporterHistoryStatus;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.feign.intf.base.service.UserFeign;
import com.luych.toolbox.common.feign.param.data.service.DataTransporterHistoryParam;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.common.feign.view.data.service.DataSourceView;
import com.luych.toolbox.common.feign.view.data.service.DataTransporterHistoryTableView;
import com.luych.toolbox.common.feign.view.data.service.DataTransporterHistoryView;
import com.luych.toolbox.common.feign.view.data.service.DataTransporterPlanView;
import com.luych.toolbox.common.page.PageParam;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseConvert;
import com.luych.toolbox.common.service.base.BaseService;
import com.luych.toolbox.common.service.exception.HttpException;
import com.luych.toolbox.common.service.page.SpringPageParamAdapter;
import com.luych.toolbox.common.service.page.SpringPageResultAdapter;
import com.luych.toolbox.data.service.constant.Constant;
import com.luych.toolbox.data.service.convert.DataTransporterHistoryEntityToView;
import com.luych.toolbox.data.service.convert.DataTransporterHistoryParamToEntity;
import com.luych.toolbox.data.service.convert.DataTransporterPlanEntityToView;
import com.luych.toolbox.data.service.dao.DataSourceDao;
import com.luych.toolbox.data.service.dao.DataTransporterHistoryDao;
import com.luych.toolbox.data.service.dao.DataTransporterHistoryTableDao;
import com.luych.toolbox.data.service.dao.DataTransporterPlanDao;
import com.luych.toolbox.data.service.entity.DataSource;
import com.luych.toolbox.data.service.entity.DataTransporterHistory;
import com.luych.toolbox.data.service.entity.DataTransporterHistoryTable;
import com.luych.toolbox.data.service.entity.DataTransporterPlan;
import com.luych.toolbox.data.service.job.DataTransporterHistoryExecuteJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.*;

@Service
public class DataTransporterHistoryService
        extends BaseService<DataTransporterHistoryView, DataTransporterHistoryParam, DataTransporterHistory>
        implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataTransporterHistoryService.class);

    private static final BaseConvert<DataTransporterHistoryParam, DataTransporterHistory> dataTransporterHistoryParamToEntity = new DataTransporterHistoryParamToEntity();
    private static final BaseConvert<DataTransporterHistory, DataTransporterHistoryView> dataTransporterHistoryEntityToView = new DataTransporterHistoryEntityToView();
    private static final BaseConvert<DataTransporterHistoryTable, DataTransporterHistoryTableView> dataTransporterHistoryTableEntityToView = DataTransporterHistoryTableView::new;
    private static final BaseConvert<DataTransporterPlan, DataTransporterPlanView> dataTransporterPlanEntityToView = new DataTransporterPlanEntityToView();
    private static final BaseConvert<DataSource, DataSourceView> dataSourceEntityToView = DataSourceView::new;

    private final Boolean rescheduleWhenStart;

    private final Scheduler scheduler;
    private final TransactionTemplate transactionTemplate;

    private final WebSocketEventPublisher eventPublisher;

    private final DataTransporterHistoryDao dataTransporterHistoryDao;
    private final DataTransporterPlanDao dataTransporterPlanDao;
    private final DataTransporterHistoryTableDao dataTransporterHistoryTableDao;
    private final DataSourceDao dataSourceDao;

    private final UserFeign userFeign;

    @Autowired
    public DataTransporterHistoryService(@Value("${spring.quartz.rescheduleWhenStart:false}") Boolean rescheduleWhenStart,
                                         Scheduler scheduler,
                                         TransactionTemplate transactionTemplate,
                                         BusProperties busProperties,
                                         ApplicationEventPublisher applicationEventPublisher,
                                         DataTransporterHistoryDao dataTransporterHistoryDao,
                                         DataTransporterPlanDao dataTransporterPlanDao,
                                         DataTransporterHistoryTableDao dataTransporterHistoryTableDao,
                                         DataSourceDao dataSourceDao,
                                         UserFeign userFeign) {
        super(dataTransporterHistoryDao, dataTransporterHistoryParamToEntity, dataTransporterHistoryEntityToView);

        this.rescheduleWhenStart = rescheduleWhenStart;
        this.scheduler = scheduler;
        this.transactionTemplate = transactionTemplate;
        this.dataTransporterHistoryDao = dataTransporterHistoryDao;
        this.dataTransporterPlanDao = dataTransporterPlanDao;
        this.dataTransporterHistoryTableDao = dataTransporterHistoryTableDao;
        this.dataSourceDao = dataSourceDao;
        this.userFeign = userFeign;

        this.eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);
    }

    @Override
    protected DataTransporterHistoryView fill(DataTransporterHistoryView view) {
        Optional<DataTransporterHistory> dataTransporterHistoryOpt = dataTransporterHistoryDao.findById(view.getId());
        dataTransporterHistoryOpt.map(DataTransporterHistory::getDataSourceFromId).flatMap(dataSourceDao::findById).map(dataSourceEntityToView).ifPresent(view::setDataSourceFrom);
        dataTransporterHistoryOpt.map(DataTransporterHistory::getDataSourceToId).flatMap(dataSourceDao::findById).map(dataSourceEntityToView).ifPresent(view::setDataSourceTo);
        dataTransporterHistoryOpt.map(DataTransporterHistory::getDataTransporterPlanId).flatMap(dataTransporterPlanDao::findById).map(dataTransporterPlanEntityToView).ifPresent(view::setDataTransporterPlan);
        dataTransporterHistoryOpt.map(DataTransporterHistory::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return super.fill(view);
    }

    private void setStatus(String id, DataTransporterHistoryStatus status) {
        DataTransporterHistory dataTransporterHistory = dataTransporterHistoryDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_COMPARE_HISTORY_NOT_FOUND));
        dataTransporterHistory.setStatus(status);
        dataTransporterHistoryDao.save(dataTransporterHistory);
    }

    private JobKey getJobKey(String id) {
        return new JobKey(id, DataTransporterHistoryExecuteJob.class.getName());
    }

    private JobDetail getJobDetail(String id) {
        Map<String, Object> jobParam = new HashMap<String, Object>() {{
            this.put("id", id);
        }};
        return JobBuilder.newJob(DataTransporterHistoryExecuteJob.class)
                .withIdentity(this.getJobKey(id))
                .usingJobData(new JobDataMap(jobParam))
                .build();
    }

    private Trigger getJobTrigger(String id) {
        return TriggerBuilder.newTrigger()
                .withIdentity(id, DataTransporterHistoryExecuteJob.class.getName())
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(1, 1))
                .build();
    }

    @Override
    public DataTransporterHistoryView create(DataTransporterHistoryParam param) {
        Assert.notNull(param.getDataSourceFromId(), "Param dataSourceFromId can't be empty");
        Assert.notNull(param.getDataSourceToId(), "Param dataSourceToId can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // save
        DataTransporterHistory dataTransporterHistoryParam = dataTransporterHistoryParamToEntity.apply(param);
        dataTransporterHistoryParam.setStatus(DataTransporterHistoryStatus.LOADING);
        DataTransporterHistory dataTransporterHistoryResult = dataTransporterHistoryDao.save(dataTransporterHistoryParam);
        DataTransporterHistoryView view = this.fill(dataTransporterHistoryEntityToView.apply(dataTransporterHistoryResult));

        // transporter
        try {
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        return view;
    }

    @Override
    public DataTransporterHistoryView modify(DataTransporterHistoryParam param) {
        throw new HttpException(HttpStatus.METHOD_NOT_ALLOWED, Constant.DATA_COMPARE_HISTORY_MODIFY_REJECT);
    }

    @Override
    public void remove(String id) {
        DataTransporterHistory dataTransporterHistory = dataTransporterHistoryDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_COMPARE_HISTORY_NOT_FOUND));
        try {
            scheduler.deleteJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }
        DataTransporterHistoryStatus oldStatus = dataTransporterHistory.getStatus();

        dataTransporterHistory.setStatus(DataTransporterHistoryStatus.REMOVING);
        dataTransporterHistoryDao.save(dataTransporterHistory);

        eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DATA_COMPARE_REMOVING, id));

        try {
            LOGGER.info("start to delete transporter result of id [{}]...", id);
            transactionTemplate.executeWithoutResult(status -> {
                dataTransporterHistoryTableDao.deleteByDataTransporterHistoryId(id);
                dataTransporterHistoryDao.deleteById(id);
            });
            LOGGER.info("success to delete transporter result of id [{}]...", id);
        } finally {
            if (dataTransporterHistoryDao.existsById(id)) {
                dataTransporterHistory.setStatus(oldStatus);
                dataTransporterHistoryDao.save(dataTransporterHistory);
            }
        }
    }

    public PageResult<DataTransporterHistoryView> pageByKeyword(PageParam pageParam, String keyword) {
        Page<DataTransporterHistory> page;
        if (StringUtils.isEmpty(keyword)) {
            page = dataTransporterHistoryDao.findAll(new SpringPageParamAdapter(pageParam));
        } else {
            page = dataTransporterHistoryDao.findByNameLike("%" + keyword + "%", new SpringPageParamAdapter(pageParam));
        }
        PageResult<DataTransporterHistory> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(dataTransporterHistoryEntityToView).convert(this::fill);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (Boolean.TRUE.equals(rescheduleWhenStart)) {
            List<DataTransporterHistoryStatus> statuses = Arrays.asList(DataTransporterHistoryStatus.LOADING, DataTransporterHistoryStatus.RUNNING);
            List<DataTransporterHistory> dataTransporterHistorys = dataTransporterHistoryDao.findByStatusIn(statuses);
            for (DataTransporterHistory dataTransporterHistory : dataTransporterHistorys) {
                try {
                    scheduler.deleteJob(this.getJobKey(dataTransporterHistory.getId()));
                    scheduler.scheduleJob(this.getJobDetail(dataTransporterHistory.getId()), this.getJobTrigger(dataTransporterHistory.getId()));
                    this.setStatus(dataTransporterHistory.getId(), DataTransporterHistoryStatus.RUNNING);
                } catch (SchedulerException e) {
                    this.setStatus(dataTransporterHistory.getId(), DataTransporterHistoryStatus.EXCEPTION);
                    throw new IllegalStateException(e);
                }
            }
        }
    }

    public PageResult<DataTransporterHistoryTableView> pageTransporterTables(PageParam pageParam, String id, Boolean transported, String table) {
        Specification<DataTransporterHistoryTable> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            Predicate historyEqual = criteriaBuilder.equal(root.get("dataTransporterHistoryId"), id);
            predicates.add(historyEqual);
            if (!StringUtils.isEmpty(table)) {
                Predicate tableOneLike = criteriaBuilder.like(root.get("tableFrom"), '%' + table + '%');
                Predicate tableTwoLike = criteriaBuilder.like(root.get("tableTo"), '%' + table + '%');
                Predicate tableLike = criteriaBuilder.or(tableOneLike, tableTwoLike);
                predicates.add(tableLike);
            }
            if (Boolean.TRUE.equals(transported)) {
                Predicate diffPredicate = criteriaBuilder.greaterThan(root.get("countTransporter"), 0);
                predicates.add(diffPredicate);
            }
            if (Boolean.FALSE.equals(transported)) {
                Predicate samePredicate = criteriaBuilder.equal(root.get("countTransporter"), 0);
                predicates.add(samePredicate);
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        Page<DataTransporterHistoryTable> page = dataTransporterHistoryTableDao.findAll(specification, new SpringPageParamAdapter(pageParam));

        PageResult<DataTransporterHistoryTable> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(dataTransporterHistoryTableEntityToView);
    }


    @Transactional
    public void truncate() {
        dataTransporterHistoryTableDao.truncate();
        dataTransporterHistoryDao.truncate();
    }
}
